package com.local.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cz073586.tools.util.Tools;
import com.local.common.PayTypeConstans;
import com.local.dao.mapers.LocalFinanceWorkMapper;
import com.local.dao.mapers.LocalStationMapper;
import com.local.dao.mapers.WorkTransitionMapper;
import com.local.entity.ex.WorkTransitionEx;
import com.local.entity.report.MemberVo;
import com.local.entity.vo.WorkPayBillVo;
import com.local.entity.vo.WorkTransationVo;
import com.local.entity.vo.WorkUserPayBillVo;
import com.local.model.AdminPayBill;
import com.local.model.LocalCoupon;
import com.local.model.LocalFinanceWork;
import com.local.model.LocalFinanceWorkExample;
import com.local.model.LocalPayBill;
import com.local.model.LocalRotaUser;
import com.local.model.LocalStation;
import com.local.model.WorkTransition;
import com.local.model.WorkTransitionExample;
import com.local.page.WorkTransitionPageInfo;
import com.local.page.report.WorkTransationVoPage;
import com.local.service.face.AdminPayBillService;
import com.local.service.face.LocalCouponService;
import com.local.service.face.LocalRotaUserService;
import com.local.service.face.LocalWorkTransService;
import com.local.service.face.ParkwellPayBillService;
import com.qianhai.common.dao.face.BaseMapper;
import com.qianhai.common.exception.BaseException;
import com.qianhai.common.service.impl.BaseServiceImpl;
import com.qianhai.common.utils.BeanUtil;
import com.qianhai.common.utils.UUIDGenerateUtil;
import com.tt.system.dao.mapers.UserMapper;

import common.cz0735.coustomer.model.CoustomerInfo;
import common.cz0735.coustomer.model.CoustomerInfoExample;
import common.cz0735.coustomer.service.face.CoustomerInfoService;

@Service
public class LocalWorkTransServiceImpl extends
		BaseServiceImpl<WorkTransitionExample, WorkTransition, String>
		implements LocalWorkTransService
{
	
	@Autowired
	private WorkTransitionMapper localWorkTransMapper;
	
	@Autowired
	private LocalFinanceWorkMapper localFinanceWorkMapper;
	
	@Autowired
	private LocalStationMapper localStationMapper;
	
	@Autowired
	private LocalRotaUserService localRotaUserService;
	
	@Autowired
	private CoustomerInfoService coustomerInfoService;
	
	
	@Autowired
	private ParkwellPayBillService parkwellPayBillService;
	@Autowired
	private AdminPayBillService adminPayBillService;
	@Autowired
	private LocalCouponService lcalCouponService;
	
	@Autowired
	private UserMapper userMapper;
	
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public List<WorkTransition> findAllLocalWorkTransByQueryForm(
			WorkTransitionPageInfo pageInfo)
	{
		try
		{
			Integer recordCount = localWorkTransMapper.countAllByPage(pageInfo);
			pageInfo.setTotalRecords(recordCount);
			List<WorkTransition> list = localWorkTransMapper
					.queryByPage(pageInfo);
			
			List<WorkTransition> listEx = new ArrayList<WorkTransition>();
			
			for (WorkTransition workTrans : list)
			{
				WorkTransitionEx ex = new WorkTransitionEx();
				BigDecimal priceInit = new BigDecimal(!Tools.isEmpty(workTrans.getRealPrice())?workTrans.getRealPrice():0d);
				workTrans.setRealPrice(priceInit.doubleValue());
				if(!Tools.isEmpty(workTrans.getWorkPeopleId())){
					
					CoustomerInfoExample custEx = new CoustomerInfoExample();
					custEx.or()
							.andLoginUserUuidEqualTo(workTrans.getWorkPeopleId());
					List<CoustomerInfo> custList = coustomerInfoService
							.selectByCondition(custEx);
					
					if (!Tools.isEmpty(custList) && !custList.isEmpty())
					{
						workTrans.setWorkPeopleName(custList.get(0).getName());
					}
					
//					User user = userMapper.selectByPrimaryKey(workTrans.getWorkPeopleId());
//					workTrans.setWorkPeopleName(!Tools.isEmpty(user)&&!Tools.isEmpty(user.getLoginName())?user.getLoginName():workTrans.getWorkPeopleName());
				}
				BeanUtil.copyProperties(ex, workTrans);
				// 转换岗亭id为岗亭名称
				LocalStation station = localStationMapper
						.selectByPrimaryKey(workTrans.getStationId());
				if (!Tools.isEmpty(station))
				{
					ex.setStateName(station.getStationName());
				}
				
				// // 转换交班人的id为交班人名称
				// CoustomerInfo coustomerInfo = coustomerInfoMapper
				// .selectByPrimaryKey(workTrans.getFromOriPeople());
				//
				// if (!Tools.isEmpty(coustomerInfo))
				// {
				// ex.setFromOriUserName(coustomerInfo.getName());
				// } else
				// {
				// User user = userMapper.selectByPrimaryKey(workTrans
				// .getFromOriPeople());
				// ex.setFromOriUserName(user.getLoginName());
				// }
				//
				// // 转换被交班人的id为被交班人名称
				// CoustomerInfo coustomerInfo1 = coustomerInfoMapper
				// .selectByPrimaryKey(workTrans.getToTirgetPeople());
				//
				// if (!Tools.isEmpty(coustomerInfo1))
				// {
				// ex.setToTargetUserName(coustomerInfo1.getName());
				// } else
				// {
				// User user1 = userMapper.selectByPrimaryKey(workTrans
				// .getToTirgetPeople());
				// ex.setToTargetUserName(user1.getLoginName());
				// }
				
				listEx.add(ex);
			}
			// ////////
			pageInfo.setData(listEx);
			return list;
		} catch (Exception e)
		{
			throw new BaseException("", e);
		}
		
	}
	
	/**
	 * 新增 工作交班
	 */
	public void addLocalWorkTrans(WorkTransition localWorkTrans)
	{
		// 验证当前上班人是否有在其他的岗亭上班，有责不允许当前上班操作
		WorkTransitionExample condition = new WorkTransitionExample();
		condition.or().andWorkPeopleIdEqualTo(localWorkTrans.getWorkPeopleId())
				.andStatusEqualTo(1);
		
		List<WorkTransition> workTransList = this.selectByCondition(condition);
		if (!Tools.isEmpty(workTransList))
		{
			throw new BaseException("50000-00001-00038");
		}
		LocalRotaUser localRotaUser = localRotaUserService.queryStationByUser(localWorkTrans.getWorkPeopleId());
		if(!Tools.isEmpty(localRotaUser)&&!localWorkTrans.getStationId().equals(localRotaUser.getStationUuid())){
			throw new BaseException("50000-00001-00066");
		}
		Date day = new Date();
		localWorkTrans.setStartworkTime(formatter.format(day));
		
		// 所属岗亭不能为空
		if (Tools.isEmpty(localWorkTrans.getStationId()))
		{
			throw new BaseException("50000-00001-00022");
		}
		
		localWorkTrans.setWorkTransUuid(UUIDGenerateUtil.generate());
		localWorkTrans.setStatus(1);
		localWorkTransMapper.insert(localWorkTrans);
	}
	
	/**
	 * 修改 工作交班 方法描述：
	 * 
	 * @Title: modifyLocalWorkTrans
	 * @param @param localWorkTrans
	 * @return void
	 * @user Administrator 2015年10月3日
	 * @throws
	 */
	@Override
	public void modifyLocalWorkTrans(WorkTransition localWorkTrans)
	{
		try
		{
			
			if (Tools.isEmpty(localWorkTrans.getWorkTransUuid()))
			{
				throw new BaseException("50000-00001-00001");
			}
			
			// 处理财务确认交班
			if (Tools.isEmpty(localWorkTrans.getStatus())
					|| localWorkTrans.getStatus() == 1)
			{
				// 修改状态为下班2
				localWorkTrans.setStatus(2);
			}
			// 设置下班时间
			Date day = new Date();
			localWorkTrans.setEndworkTime(formatter.format(day));
			localWorkTransMapper.updateByPrimaryKeySelective(localWorkTrans);
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage());
		}
	}
	
	@Override
	public BaseMapper<WorkTransitionExample, WorkTransition, String> getMapper()
	{
		return localWorkTransMapper;
	}
	
	@Override
	public WorkTransition showWorkTrans(WorkTransition workTransition)
	{
		
		if (Tools.isEmpty(workTransition.getStationId()))
		{
			new Throwable("50000-00001-00022");
		}
		
		// 查找是否有上班记录
		WorkTransitionExample condition = new WorkTransitionExample();
		condition.or()
				// .andWorkPeopleIdEqualTo(workTransition.getWorkPeopleId())
				.andStatusEqualTo(1)
				.andStationIdEqualTo(workTransition.getStationId());
		
		List<WorkTransition> workTransList = this.selectByCondition(condition);
		WorkTransition worktransititon = null;
		// WorkTransitionEx worktrans = new WorkTransitionEx();
		// worktrans.setWorking(false);
		
		if (!Tools.isEmpty(workTransList) && !workTransList.isEmpty())
		{
			worktransititon = workTransList.get(0);
			
			Date date = null;
			if (!Tools.isEmpty(worktransititon.getStartworkTime().trim()))
			{
				
				try
				{
					date = formatter.parse(worktransititon.getStartworkTime());
				} catch (ParseException e)
				{
					new Throwable("50000-00001-00024");
				}
			}
			
			// worktransititon.setWorking(true);
			
			// // 显示排班信息 如果当前当班人存在早班，晚班两个班信息，那应该显示排班信息的结束时间大于当前交班里面的上班时间。
			// LocalRota conditionrota = new LocalRota();
			// conditionrota.setUserId(workTransition.getWorkPeopleId());
			// conditionrota.setEndTime(worktrans.getStartworkTime());
			// LocalRota rotaResult = localRotaService
			// .queryLocalRotaByUserId(conditionrota);
			//
			// if (Tools.isEmpty(rotaResult))
			// {
			// new Throwable("50000-00001-00023");
			// }
			// worktrans.setArrangeWorkUuid(rotaResult.getUuid());
			// // 显示排班信息 end
			//
			LocalPayBill payBill = new LocalPayBill();
			payBill.setUserId(worktransititon.getWorkPeopleId());
			
			payBill.setPayTime(date);
			
			// 取流水表的现金金额price
			payBill.setPayType(PayTypeConstans.MONEY_TYPE);
			Double payBllPrice = parkwellPayBillService
					.queryPayBillByCondition(payBill);
			worktransititon.setMoney(payBllPrice);
			
			// 取流水表的移动支付金额price
			payBill.setPayType(PayTypeConstans.MOBILE_TYPE);
			Double movePayPrice = parkwellPayBillService
					.queryPayBillByCondition(payBill);
			worktransititon.setMovePayMoney(movePayPrice);
			
			// 统计强制开闸次数
			AdminPayBill adminPayBill = new AdminPayBill();
			adminPayBill.setPayTime(date);
			adminPayBill.setLonginUserUuid(worktransititon.getWorkPeopleId());
			Integer countSize = adminPayBillService
					.queryAdminPayBillCountByLoginUserId(adminPayBill);
			worktransititon.setCutOffCount(Double.valueOf(countSize));
			
			// 取抵用卷金额 groupon_money
			LocalCoupon localCoupon = new LocalCoupon();
			localCoupon.setUserId(worktransititon.getWorkPeopleId());
			localCoupon.setPayTime(date);
			Double couponPrice = lcalCouponService
					.queryCouponPriceByLoginUserId(localCoupon);
			worktransititon.setGrouponMoney(couponPrice);
			
			// 应收 =payBllPrice + movePayPrice + couponPrice;
			double shouldPrice = 0.0;
			if (!Tools.isEmpty(payBllPrice))
			{
				
				shouldPrice += payBllPrice.doubleValue();
			}
			if (!Tools.isEmpty(movePayPrice))
			{
				shouldPrice += movePayPrice.doubleValue();
			}
			
			if (!Tools.isEmpty(couponPrice))
			{
				shouldPrice += couponPrice.doubleValue();
			}
			
			// 实收=应收-优惠券
			double realPrice = payBllPrice==null?0:payBllPrice.doubleValue();
			/*if (!Tools.isEmpty(couponPrice) && shouldPrice > 0.0)
			{
				realPrice = shouldPrice - couponPrice.doubleValue();
			}
			*/
			worktransititon.setShouldPrice(Double.valueOf(shouldPrice));
			worktransititon.setRealPrice(Double.valueOf(realPrice));
			
		}
		if(!Tools.isEmpty(worktransititon)&&!Tools.isEmpty(worktransititon.getWorkTransUuid())){
			this.updateWorkTransitionByUuid(worktransititon);
		}
		return worktransititon;
	}
	
	/** 
	 * 方法描述：更新上班情况说明
	 * @Title: updateWorkTransitionByUuid 
	 * @param @param worktransititon
	 * @return void
	 * @user pichunhan
	 * 2016年4月17日
	 * @throws
	 */
	private void updateWorkTransitionByUuid(WorkTransition worktransititon) {
		localWorkTransMapper.updateByPrimaryKeySelective(worktransititon);
	}

	@Override
	public WorkTransationVo findWorkTransitonByuuid(String uuid)
	{
		WorkTransition workTrans = localWorkTransMapper.selectByPrimaryKey(uuid);
		
		WorkTransationVo wv=null;
		try
		{
			if (!Tools.isEmpty(workTrans))
			{
				WorkTransitionEx ex = new WorkTransitionEx();
				if(!Tools.isEmpty(workTrans.getWorkPeopleId())){
					CoustomerInfo ci=coustomerInfoService.getCustmoerByLoginId(workTrans.getWorkPeopleId());
					/*User user = userMapper.selectByPrimaryKey(workTrans.getWorkPeopleId());*/
					workTrans.setWorkPeopleName(!Tools.isEmpty(ci)&&!Tools.isEmpty(ci.getName())?ci.getName():"无");
					workTrans.setUserId(!Tools.isEmpty(ci)&&!Tools.isEmpty(ci.getUuid())?ci.getUuid():null);
				}
				BeanUtil.copyProperties(ex, workTrans);
				// 转换岗亭id为岗亭名称
				LocalStation station = localStationMapper.selectByPrimaryKey(workTrans.getStationId());
				if (!Tools.isEmpty(station))
				{
					ex.setStateName(station.getStationName());
				}
				wv=returnWorkTransationVo(ex);
				List<WorkPayBillVo> li=returnWorkPayBillVo(wv);
				wv.setWorkPayBillVos(li);
				rtu(wv, li);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
			throw new BaseException("----------转换失败---------");
		}
		return wv;
	}
	
	public WorkTransationVo returnWorkTransationVo(WorkTransitionEx we){
		WorkTransationVo wv=new WorkTransationVo();
		try
		{
			SimpleDateFormat c=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			wv.setUserName(we.getWorkPeopleName());
			wv.setStationUuid(we.getStationId());
			wv.setStationName(we.getStateName());
			wv.setStartTime(we.getStartworkTime());
			wv.setEndTime(we.getEndworkTime());
			wv.setRotaStartTime(we.getStartworkTime());
			wv.setRotaEndTime(Tools.isEmpty(we.getEndworkTime())?c.format(new Date()):we.getEndworkTime());
			
		} catch (Exception e)
		{
			return null;
		}
		return wv;
	}
	
	public List<WorkPayBillVo> returnWorkPayBillVo(WorkTransationVo wv){
		WorkPayBillVo wb=new WorkPayBillVo();
		
		SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<WorkPayBillVo> list=new ArrayList<WorkPayBillVo>();
		
		//根据人员统计，有多少总钱
		List<WorkUserPayBillVo> li=parkwellPayBillService.countUserBill(wv.getStationUuid(),wv.getStartTime(), !Tools.isEmpty(wv.getEndTime())?wv.getEndTime():sd.format(new Date()));
		if(!Tools.isEmpty(li)&&li.size()>0){
			for(WorkUserPayBillVo wpb:li){
				WorkPayBillVo wpv=new WorkPayBillVo();
				wpv.setUserName(wpb.getUserName());
				wpv.setTotalMoney(wpb.getPrice());
				list.add(wpv);
			}
			
		List<WorkUserPayBillVo> listType=parkwellPayBillService.countUserAndTypeBill(wv.getStationUuid(),wv.getStartTime(), !Tools.isEmpty(wv.getEndTime())?wv.getEndTime():sd.format(new Date()));
			for(WorkPayBillVo workPayBillVo:list){
				for(WorkUserPayBillVo workUserPayBillVo:listType){
					if(workPayBillVo.getUserName().equalsIgnoreCase(workUserPayBillVo.getUserName())){
						if(workUserPayBillVo.getPayType().equalsIgnoreCase("移动支付")){
							workPayBillVo.setMobileMoney(workUserPayBillVo.getPrice());
						}
						if(workUserPayBillVo.getPayType().equalsIgnoreCase("抵用劵")){
							workPayBillVo.setBusinessMoney(workUserPayBillVo.getPrice());
						}
						if(workUserPayBillVo.getPayType().equalsIgnoreCase("现金")){
							workPayBillVo.setMoney(!Tools.isEmpty(workUserPayBillVo.getActualPrice())?workUserPayBillVo.getActualPrice():workUserPayBillVo.getPrice());
						}
						if(workUserPayBillVo.getPayType().equalsIgnoreCase("电子代金劵")){
							workPayBillVo.setTechMoney(workUserPayBillVo.getPrice());
						}
						//纸质优惠卷
						if(!Tools.isEmpty(workUserPayBillVo.getActualPrice())){
							workPayBillVo.setPaperPreferential(workUserPayBillVo.getPrice()-workUserPayBillVo.getActualPrice());
						}
					}
					workPayBillVo.setStartTime(!Tools.isEmpty(wv.getStartTime())?wv.getStartTime():null);
					workPayBillVo.setEndTime(!Tools.isEmpty(wv.getEndTime())?wv.getEndTime():null);
				}
			}
		}
		return list;
	}
	
	public WorkTransationVo rtu(WorkTransationVo wts,List<WorkPayBillVo> li){
		Double totalMoney = 0.0;
		Double money = 0.0;
		//商家抵用卷
		Double businessMoney = 0.0;
		//电子抵用卷
		Double techMoney = 0.0;
		//纸质优惠卷
		Double paperPreferential = 0.0;
		//移动支付
		Double mobileMoney = 0.0;
		//强制开闸
		Integer cutOffCount = 0;
		for(WorkPayBillVo wv:li){
			totalMoney+=wv.getTotalMoney();
			money+=wv.getMoney();
			businessMoney+=wv.getBusinessMoney();
			techMoney+=wv.getTechMoney();
			paperPreferential+=wv.getPaperPreferential();
			mobileMoney+=wv.getMobileMoney();
			cutOffCount+=wv.getCutOffCount();
		}
		wts.setTotalMoney(totalMoney);
		wts.setMoney(money);
		wts.setBusinessMoney(businessMoney);
		wts.setTechMoney(techMoney);
		wts.setPaperPreferential(paperPreferential);
		wts.setMobileMoney(mobileMoney);
		wts.setCutOffCount(cutOffCount);
		return wts;
	}

	@Override
	public void confirmWorkTransiton(LocalFinanceWork localFinanceWork)
	{
		// TODO Auto-generated method stub
		if(!Tools.isEmpty(localFinanceWork)){
			localFinanceWork.setUuid(UUIDGenerateUtil.generate());
			localFinanceWork.setStatus(localFinanceWork.getStatus());
			localFinanceWork.setCreateTime(new Date());
			localFinanceWorkMapper.insertSelective(localFinanceWork);
		}
		
		WorkTransition workTransition=localWorkTransMapper.selectByPrimaryKey(localFinanceWork.getWorkTransitionUuid());
		workTransition.setStatus(3);// 财务确认交班
		localWorkTransMapper.updateByPrimaryKey(workTransition);
	}

	@Override
	public LocalFinanceWork queryFinanceByWorkId(String workUuid)
	{
		// TODO Auto-generated method stub
		LocalFinanceWorkExample condtion = new LocalFinanceWorkExample();
		condtion.or().andWorkTransitionUuidEqualTo(workUuid);
		List<LocalFinanceWork> list=localFinanceWorkMapper.selectByCondition(condtion);
		return !Tools.isEmpty(list)&&list.size()>0?list.get(0):null;
	}

	@Override
	public com.local.entity.report.WorkTransationVo queryWorkReport(WorkTransationVoPage<com.local.entity.report.WorkTransationVo> pageinfo)
	{
		com.local.entity.report.WorkTransationVo wv=localWorkTransMapper.queryWorkTransationVo(pageinfo);
		
		// TODO Auto-generated method stub
		return wv;
	}
}
